<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-row :gutter="20">
              <a-col :span="5">
                <a-form-item field="title" label="消息标题">
                  <a-input
                    v-model="formModel.title"
                    placeholder="请输入消息标题"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <!-- <a-col :span="5">
                <a-form-item field="username" label="时间">
                  <a-range-picker @change="onChangeTime" />
                </a-form-item>
              </a-col> -->
              <a-col :span="5">
                <a-space :size="18">
                  <a-button @click="openAdd()" type="primary">
                    <template #icon>
                      <icon-plus />
                    </template>
                    新增
                  </a-button>
                  <a-button type="primary" @click="onPageChange(1)">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                  <!-- <a-button type="primary" @click="openOper">
										操作日志
									</a-button> -->
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="userId"
        :loading="loading"
        page-position="bottom"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #option="{ record }">
          <a-space :size="18">
            <a-button @click="openEdit(record)" type="outline">
              编辑信息
            </a-button>
            <a-button @click="del(record)" type="primary" status="danger">
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 添加菜单 -->
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
    >
      <template #title> 分类 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-form-item field="title" label="消息标题">
          <a-input
            v-model="addForm.title"
            size="large"
            placeholder="请输入消息标题"
          />
        </a-form-item>
        <a-form-item field="content" label="消息内容">
          <a-textarea
            class="contdg"
            v-model="addForm.content"
            size="large"
            placeholder="请输入消息内容"
          />
        </a-form-item>
        <a-form-item
          field="orgId"
          label="通知班级"
          v-if="addForm.createTime == ''"
        >
          <a-tree-select
            v-model="addForm.orgId"
            :max-tag-count="2"
            :only-check-leaf="true"
            :allow-clear="true"
            :allow-search="true"
            :data="treeData"
            placeholder="请选择通知班级"
            :fieldNames="{
              key: 'id',
              title: 'name',
              children: 'children',
            }"
            style="width: 420px"
          ></a-tree-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import { useRouter } from 'vue-router';
  import useLoading from '@/hooks/loading';
  import {
    Message,
    Modal,
    TableColumnData,
    ValidatedError,
  } from '@arco-design/web-vue';
  import { organizationTree } from '@/api/examine';
  import { outlist, outAdd, outUpdate, outDel } from '@/api/outbox';
  import { Pagination } from '@/types/global';
  const { loading, setLoading } = useLoading(true);
  // 类似接口 非接口
  const generateFormModel = () => {
    return {
      title: '',
      //   startTime: '',
      //   endTime: '',
    };
  };

  //   重置
  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };
  //   定义相关参数
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  //   查找 充实

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };
  const renderData = ref([]);
  //   定义查询接口
  const treeData = ref([]);
  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      outlist(data).then((res) => {
        renderData.value = res.data.list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;
      });
      organizationTree({}).then((res: any) => {
        if (res.code == 200) {
          treeData.value = res.data;
        }
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const formModel = ref(generateFormModel());

  const columns = computed<TableColumnData[]>(() => [
    {
      title: 'ID',
      dataIndex: 'msgOutId',
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '内容',
      dataIndex: 'content',
      ellipsis: true,
      width: 700,
    },
    {
      title: '发送人',
      dataIndex: 'createUserName',
    },
    {
      title: '发送时间',
      dataIndex: 'createTime',
    },

    {
      title: '功能',
      slotName: 'option',
    },
  ]);
  const addShow = ref(false);
  //   新增
  const openAdd = () => {
    addShow.value = true;
  };
  const generateDataModel = () => {
    return {
      title: '',
      content: '',
      orgId: '',
      msgOutId: '',
      createTime: '',
    };
  };
  const addForm = ref(generateDataModel());
  const openEdit = (item: any) => {
    addForm.value = Object.assign({}, item);
    addShow.value = true;
  };
  fetchData();

  const handleCancel = () => {
    addForm.value = generateDataModel();
  };
  const addModel = ref();
  const handleCheck = (done: (arg0: boolean) => void) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.msgOutId) {
            outUpdate({
              title: addForm.value.title,
              msgOutId: addForm.value.msgOutId,
              content: addForm.value.content,
              orgId: addForm.value.orgId,
            }).then((res: any) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '编辑成功',
                });
                addForm.value = generateDataModel();
                done(true);
                fetchData();
              } else {
                done(false);
              }
            });
          } else {
            outAdd({
              title: addForm.value.title,
              content: addForm.value.content,
              orgId: addForm.value.orgId,
            }).then((res: any) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '新增成功',
                });
                addForm.value = generateDataModel();
                done(true);
                fetchData();
              } else {
                done(false);
              }
            });
          }
        } else {
          done(false);
        }
      }
    );
  };
  const rules = {
    title: [
      {
        required: true,
        message: '请输入消息标题',
      },
      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
    content: [
      {
        required: true,
        message: '消息内容',
      },
    ],
    orgId: [
      {
        required: true,
        message: '组织机构',
      },
    ],
  };

  const del = (item: any) => {
    outDel({
      msgOutId: item.msgOutId,
    }).then((res: any) => {
      if (res.code == 200) {
        Message.success('删除成功');
        fetchData();
      }
    });
  };
</script>

<style scoped></style>
